#!/bin/bash
set -eu

TESTDIR=$(readlink -f $(dirname $0))
. $TESTDIR/framework

setupenvironment

buildpackage 'simple-package'

readonly P=simple-package-update
readonly N=$(( 1024 + 100 ))
build_P()
{
    local -r i="$1"; shift

    local F="$(mktemp "${TESTDIRECTORY}/specs/$P-XXXX.spec")"
    F="${F%.spec}"
    local -r F
    addtrap 'rm -f %q.{spec,metainfo}' "$F"

    # Instead of editing the spec-file, we could perhaps use rpmbuild --define.
    sed -E \
	-e 's/^Version:[[:space:]]* 2$/'"Version: $i/" \
	-e 's/ 2-alt1$/'" $i-alt1/" \
	<"${TESTDIRECTORY}/specs/$P.spec" \
	>|"$F.spec"
    sed -E \
	-e 's/version=2$/'"version=$i/" \
	<"${TESTDIRECTORY}/specs/$P.metainfo" \
	>|"$F.metainfo"
    buildpackage "${F##*/}"
}

if [ -z "${PARALLEL_SLOT-}" ]; then
    # We are not run in parallel under xargs,
    # so we can use parallelism for a speed-up here.
    NPROC="$(nproc)"
    readonly NPROC
    busy=0
    for (( I=2; I <= N; ++I )); do
	if (( ++busy > NPROC )); then
	    wait -n
	    (( --busy )) ||:
	fi
	{ CURRENTTRAP=; build_P "$I"; } &
    done
else
    # Do not use parallelism inside parallelism,
    # otherwise fork would become unavailable.
    for (( I=2; I <= N; ++I )); do
	(CURRENTTRAP=; build_P "$I"); [ 0 -eq $? ] # bash3 workaround
    done
fi

buildpackage 'conflicting-package-one'
buildpackage 'conflicting-package-distupgrade'

testpkgnotinstalled 'simple-package'
testpkgnotinstalled 'conflicting-package-one'
aptgetinstallpackage 'simple-package'
aptgetinstallpackage 'conflicting-package-one'
testpkginstalled 'simple-package'
testpkginstalled 'conflicting-package-one'

testequal '1-alt1' getpackageversion 'simple-package'
testequal '1-alt1' getpackageversion 'conflicting-package-one'

wait # we don't care much whether a few (up to 99) of the build_P's failed
generaterepository_and_switch_sources "$TMPWORKINGDIRECTORY/usr/src/RPM/RPMS"

testsuccess aptget update

# At least, it fails on assertion instead of badly overflowing the buffer.
testregexmatch '.*: Assertion .* failed\.' aptget dist-upgrade -y
testfailure

# More correct behavior would be:
#testsuccess aptget dist-upgrade -y
#testequal "$N-alt1" getpackageversion 'simple-package'
#testequal '1-alt1' getpackageversion 'conflicting-package-one'
